//
//  TextField.swift
//  MoyoungCommon
//
//  Created by 李然 on 2022/7/19.
//

import UIKit
import RxSwift
import NSObject_Rx

open class TextField: UITextField {

    override init(frame: CGRect) {
        super.init(frame: frame)
        makeUI()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        makeUI()
    }
    
    open func makeUI() {
        rightViewMode = .whileEditing
        
        self.addTarget(self, action: #selector(textValueChanged(_:)), for: .editingChanged)
        self.addTarget(self, action: #selector(textBeginEdit(_:)), for: .editingDidBegin)
        
        self.clearButton.rx.tap.subscribe(onNext: { [weak self] _ in
            guard let `self` = self else { return }
            self.text = ""
            self.rightView = nil
        }).disposed(by: rx.disposeBag)
    }

    private lazy var clearView: View = {
        let view = View()
        view.addSubview(clearButton)
        clearButton.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.greaterThanOrEqualTo(40)
            make.height.greaterThanOrEqualTo(40)
        }
        return view
    }()
    
    private lazy var clearButton: Button = {
        let clearBtn = Button(type: .custom)
        clearBtn.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        return clearBtn
    }()
    
    @objc private func textValueChanged(_ textF: TextField) {
        textF.rightView = textF.text?.count == 0 ? nil : self.clearView
    }
    
    @objc private func textBeginEdit(_ textF: TextField) {
        textF.rightView = textF.text?.count == 0 ? nil : self.clearView
    }
}

extension  UITextField {
    
    /// 过滤预输入后的普通文本
    public var normalText: String? {
        if let textRange = markedTextRange {
            if textRange.isEmpty {
                return text
            } else {
                if var text = text {
                    let location = self.offset(from: self.beginningOfDocument, to: textRange.start)
                    let length = self.offset(from: textRange.start, to: textRange.end)
                    let nsRange = NSRange(location: location, length: length)
                    if let range = Range.init(nsRange, in: text) {
                        text.replaceSubrange(range, with: "")
                        return text
                    }
                }
                return text
            }
        } else {
            return text
        }
    }
    
    /// 更新文本（不一样才更新）
    private func updateTextIfNeed(_ text: String?) {
        if normalText != text {
            self.text = text
        }
    }
    
    public func limit(_ count: Int) {
        self.rx.controlEvent(.editingChanged).bind { [weak self] _ in
            guard let self = self else {return}
            if let normalText = self.normalText, normalText.count > count {
                 let index = normalText.index(normalText.startIndex, offsetBy: count)
                 let newText = String(normalText[..<index])
                 self.updateTextIfNeed(newText)
             }
        }.disposed(by: rx.disposeBag)
    }
}
